<template>
  <el-select
    v-model="currentValue"
    :size="size"
    :multiple="multiple"
    :filterable="filterable"
    remote
    reserve-keyword
    :placeholder="placeholder"
    :remote-method="remoteMethod"
    :loading="loading"
    :disabled="disabled"
    @change="changeSelect"
    :allow-create="allowCreate"
    :clearable="clearable"
  >
    <el-option
      v-for="item in options"
      :key="item[optionValue]"
      :label="item[optionLabel]"
      :value="item[optionValue]">
    </el-option>
  </el-select>
</template>

<script>
  import { listContractCategory as listMethod } from "@/api/lease/ContractCategory";
  export default {
    model: {
      prop: 'value',
      event: 'cv'
    },
    data() {
      return {
        options: [],
        loading: false,
        currentValue: this.value,
      }
    },
    watch: {
      value(val) {
        if(this.multiple){
          this.currentValue = this.formatJson(val);
        }else{
          this.currentValue = val;
        }
      }
    },
    mounted() {
     this.remoteMethod()
    },
    methods: {
      remoteMethod(query) {
        if (query !== '') {
          this.loading = true;
          let params = {...this.queryParams,...{}}
          if(this.filterable){
            params['pageNum'] = 1
            params['pageSize'] = 10
          }
          params[this.filterCode] = query
          listMethod(params).then(res=>{
            this.loading = false;
            this.options = res.rows
          })
        } else {
          this.options = [];
        }
      },
      changeSelect: function (v) {
        if (this.multiple) {
          this.$emit('cv', this.toJson(v));
        } else {
          this.$emit('cv', v);
        }
      },
      formatJson(str) {
        if (str && str.length > 0) {
          return str.split(",");
        }
        return str;
      },
      toJson(obj) {
        let vals = [];
        obj.forEach(v=>{vals.push(v)})
        return vals.join(",");
      }
    },

    props: {
      placeholder: {
        type: String,
        default:'请输入合同类型'
      },
      value: {
        type: [String, Array, Number]
      },
      disabled: {
        type: Boolean,
        default: false
      },
      multiple: {
        type: Boolean,
        default: false
      },
      allowCreate: {
        type: Boolean,
        default: false
      },
      clearable: {
        type: Boolean,
        default: true
      },
      width: {
        type: Number
      },
      filterCode: {
        type: String,
        default:'typeName'
      },
      optionValue: {
        type: String,
        default: 'id'
      },
      optionLabel: {
        type: [String , Array ],
        default: 'typeName'
      },
      queryParams: {
        type:Object,
        default:()=>{}
      },
      size:{
        type: String,
        default:'small'
      },
      filterable:{
        type: Boolean,
        default: false
      }
    }
  }
</script>
